using DatabaseManager.Controllers;
using DatabaseManager.Services;
using DatabaseManager.Filters;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews(); // 添加 MVC 服务
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo
    {
        Title = "Database Manager API",
        Version = "v1",
        Description = "SQL Server 数据库管理系统 API - 类似阿里云 RDS 管理功能"
    });
});

// 添加会话支持
builder.Services.AddSession(options =>
{
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
    options.IdleTimeout = TimeSpan.FromMinutes(30);
});

// 配置 CORS
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader();
    });
});

// 注册认证服务
builder.Services.Configure<AdminCredentials>(
    builder.Configuration.GetSection("AdminCredentials"));
builder.Services.AddScoped<IAuthenticationService, AuthenticationService>();

// 注册认证过滤器
builder.Services.AddScoped<AdminAuthorizationFilter>();

// 注册数据库管理服务
builder.Services.AddScoped<DatabaseManagementService>(sp =>
{
    var connectionString = "Server=.;Database=master;User Id=sa;Password=123123;TrustServerCertificate=True;MultipleActiveResultSets=true";
    return new DatabaseManagementService(connectionString);
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "Database Manager API v1");
        c.RoutePrefix = "api"; // 将 Swagger UI 移到 /api 路径
    });
}

app.UseCors("AllowAll");

// 添加静态文件支持
app.UseStaticFiles();

app.UseHttpsRedirection();

// 使用会话 - 必须在 UseRouting 之前
app.UseSession();

// 添加路由支持
app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.MapControllers();

app.Run();